﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace OnlineCellphoneStore
{
    public partial class Main : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Cookies["ClientID"] != null)
                {
                    // Start User Context
                    UserContext();
                }
                else
                {
                    // Start Anonymous Context
                    AnonymousContext();
                }
            }
            if (Request.QueryString["LogOut"] == "true")
            {
                LogOutFromPage();
            }
        }
        protected void LogOut_Click(object sender, EventArgs e)
        {
            string Url = "Main.aspx?LogOut=true";
            Response.Redirect(Url, false);
        }
        private void LogOutFromPage()
        {
            // End the current session
            Session.Abandon();
            // Delete cookies
            HttpCookie IDCookie = new HttpCookie("ClientID");
            HttpCookie TimeCookie = new HttpCookie("LastVisit");
            IDCookie.Expires = DateTime.Now.AddDays(-1d);
            TimeCookie.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(IDCookie);
            Response.Cookies.Add(TimeCookie);
            Response.Redirect("Main.aspx", false);
        }
        private void UserContext()
        {
            if (Session.Count == 0)
            {
                GetUserDetails();
            }
            HandleUserLables();
            AddPurchaseNavigator();
            GetUserFavoritesProducts();
        }
        private void AnonymousContext()
        {
            HandleAnonymousLables();
            GetLatestProductsAdded();
        }
        private void HandleAnonymousLables()
        {
            DataHeading.InnerHtml = "Latest Cellphones Added";
            ShopingCartLink.Attributes.Add("href", "Account/Login.aspx");
        }
        private void GetLatestProductsAdded()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                DAL.DBAdapter.CellphonesDataTable dt = SQLAdapter.GetLatestProductsAdded();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int Id = dt[i].CellphoneID;
                    string Name = dt[i].Name;
                    double Price = dt[i].Price;
                    string UrlPicture = dt[i].PicturePath;
                    sb.Append("<div class=\"col-sm-4 col-md-4\">" +
                                  "<div class=\"thumbnail\">" +
                                        "<img width=\"250\" height=\"250\" class=\"img-thumbnail\" src=\"" + UrlPicture + "\"/>" +
                                        "<div class=\"caption text-center\">" +
                                            "<h3>" + Name + "</h3>" +
                                            "<p><strong>Price: </strong>" + Price + " NIS</p>" +
                                            "<p class=\"text-center\">" +
                                                "<a href=\"Account/Login.aspx\" class=\"btn btn-danger\" role=\"button\"><span class=\"glyphicon glyphicon-gift\"></span> " +
                                                    "Add to Cart</a> <a href=\"Info.aspx?ProductID=" + Id + "\" class=\"btn btn-primary\" role=\"button\"><span class=\"glyphicon glyphicon-info-sign\"></span>" +
                                                    " More Info</a>" +
                                            "</p>" +
                                        "</div>" +
                                   "</div>" +
                                "</div>");
                }
                DataContainerDiv.InnerHtml = sb.ToString();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

            }
        }
        private void GetUserDetails()
        {
            try
            {
                int Id = Int32.Parse(Request.Cookies["ClientID"].Value.ToString());

                // Get UserName and LastVisit from Database
                List<string> l = SQLAdapter.GetUserNameAndLastVisit(Id);
                string UserName = l[0];
                string LastVisit = l[1];

                Session["ClientID"] = Id;
                Session["LastVisit"] = LastVisit;
                Session["UserName"] = UserName;

                // Update this visit
                SQLAdapter.UpdateLastVisit(Id, DateTime.Now);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private void HandleUserLables()
        {
            // Update labels
            anonymousUserOptions.Attributes.CssStyle.Value = "display: none;";
            registerdUserOptions.Attributes.CssStyle.Value = "display: inline;";
            aHelloUser.InnerHtml += Session["UserName"].ToString();
            aLastEntered.InnerHtml += Session["LastVisit"].ToString();
            ShopingCartLink.Attributes.Add("href", "UserPages/ShopingCart.aspx");
            DataHeading.InnerHtml = "Recommended Cellphones for You";
        }
        private void GetUserFavoritesProducts()
        {
            try
            {
                int Id = Int32.Parse(Session["ClientID"].ToString());
                StringBuilder sb = new StringBuilder();
                DAL.DBAdapter.FavoriteCellphonesDataTable dt = SQLAdapter.GetFavoriteCellphones(Id);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int CellphoneId = dt[i].CellphoneID;
                    string Name = dt[i].Name;
                    double Price = dt[i].Price;
                    string UrlPicture = dt[i].PicturePath;
                    sb.Append("<div class=\"col-sm-4 col-md-4\">" +
                                  "<div class=\"thumbnail\">" +
                                        "<img width=\"250\" height=\"250\" class=\"img-thumbnail\" src=\"" + UrlPicture + "\"/>" +
                                        "<div class=\"caption text-center\">" +
                                            "<h3>" + Name + "</h3>" +
                                            "<p><strong>Price: </strong>" + Price + " NIS</p>" +
                                            "<p class=\"text-center\">" +
                                                "<a href=\"UserPages/ShopingCart.aspx?ProductID=" + CellphoneId + "\" class=\"btn btn-danger\" role=\"button\"><span class=\"glyphicon glyphicon-gift\"></span> " +
                                                    "Add to Cart</a> <a href=\"Info.aspx?ProductID=" + CellphoneId + "\" class=\"btn btn-primary\" role=\"button\"><span class=\"glyphicon glyphicon-info-sign\"></span>" +
                                                    " More Info</a>" +
                                            "</p>" +
                                        "</div>" +
                                   "</div>" +
                                "</div>");
                }
                DataContainerDiv.InnerHtml = sb.ToString();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private void AddPurchaseNavigator()
        {
            HtmlGenericControl li = new HtmlGenericControl("li");
            HtmlGenericControl anchor = new HtmlGenericControl("a");
            HtmlGenericControl span = new HtmlGenericControl("span");
            HtmlGenericControl text = new HtmlGenericControl("span");

            string Url = "UserPages/PreviousPurchase.aspx";
            anchor.ID = "RecentPurchasesLink";
            anchor.Attributes.Add("href", Url);
            text.InnerText = " My Previous Purchase";
            span.Attributes.Add("class", "glyphicon glyphicon-th-large");

            anchor.Controls.Add(span);
            anchor.Controls.Add(text);
            li.Controls.Add(anchor);
            NavBar.Controls.Add(li);
        }
    }
}